package com.nic.view.widget;

import android.content.Context;
import android.media.MediaPlayer;
import android.os.Build;
import android.support.annotation.Nullable;
import android.support.annotation.RequiresApi;
import android.text.TextUtils;
import android.util.AttributeSet;
import android.util.Base64;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.nic.view.R;
import com.nic.view.adapter.RecordAdapter;
import com.nic.view.util.Anticlockwise;
import com.nic.view.util.Utility;

import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.List;

/**
 * 录音采集
 * 1、语音录制按下、停止、中间动画、时间记录、删除、播放
 * 2、本地预览播放、在线下载后预览播放
 * Created by Administrator on 2018/8/22.
 */

public class TakeRecordingView extends LinearLayout implements AdapterView.OnItemClickListener {
    private final int TIME_LENGTH = 60;

    private ListView mlv_rec;//录音显示列表
    private Button mBtn_rec;//录音按钮
    private TextView text;//文字显示
    private RecordAdapter mRecordAdapter;
//    private ArrayList<RecordBean> mData;//适配器加载的数据


    private String fileName = "";
    private String filePath = "";
    private AudioRecorder mAudioRecorder;
    //标示是否删除文件
    private String state;

    public String getState() {
        return state;
    }

    public void setState(String state) {
        this.state = state;
    }

    private VoiceDialog voiceToast;
    private Anticlockwise mAnticlockwise;//倒计时控件

    public List<String> getVoicePathList() {
        return mRecordAdapter.getVoicePathList();
    }

    public String getPaths() {
        if (getVoicePathList().isEmpty()) {
            return "";
        }
        return TextUtils.join(",", getVoicePathList());
    }

    private Context context;

    public TakeRecordingView(Context context) {
        super(context);
    }

    public TakeRecordingView(Context context, @Nullable AttributeSet attrs) {
        super(context, attrs);
        this.context = context;
        LayoutInflater.from(context).inflate(R.layout.layout_take_record, this);
        mlv_rec = (ListView) findViewById(R.id.lv_rec); // 显示录音
        mBtn_rec = (Button) findViewById(R.id.btn_rec); // 长按录音
        text = (TextView) findViewById(R.id.text);
        mBtn_rec.setOnTouchListener(luyinTouch);
        //初始化适配器
        mRecordAdapter = new RecordAdapter(context);
        mlv_rec.setAdapter(mRecordAdapter);
        voiceToast = new VoiceDialog(context);
        mAnticlockwise = voiceToast.getAnticlockwise();//获取倒计时
        mAnticlockwise.setOnTimeCompleteListener(mListener);//倒计时结束回调监听

    }

    public TakeRecordingView(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
    }

    @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
    public TakeRecordingView(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) {
        super(context, attrs, defStyleAttr, defStyleRes);
    }

    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {

    }

    /**
     * 倒计时结束回调方法
     */
    private Anticlockwise.OnTimeCompleteListener mListener = new Anticlockwise.OnTimeCompleteListener() {
        @Override
        public void onTimeComplete() {
            //停止录音
            stopRecord();
        }
    };
    /**
     * 录音按钮的触摸事件
     */
    private OnTouchListener luyinTouch = new OnTouchListener() {
        @Override
        public boolean onTouch(View v, MotionEvent event) {
            switch (event.getAction()) {
                case MotionEvent.ACTION_DOWN:
                    if ((System.currentTimeMillis() - starMillis) == 60 * 1000) {
                        text.setText("按住说话");
                        stopRecord();
                        return false;
                    }
                    text.setText("松开结束");
                    startRecord();
                    break;
                case MotionEvent.ACTION_UP:
                case MotionEvent.ACTION_CANCEL:
                    text.setText("按住说话");
                    stopRecord();
                    break;
                case MotionEvent.ACTION_MOVE:
                    break;
            }
            return false;
        }
    };
    /**
     * true正在录音
     * false没有录音
     */
    private boolean isRecord = false;
    /**
     * 开始时间
     * 结束时间
     */
    private long starMillis = 0;
    private long endMillis = 0;

    /**
     * 开始录音
     */
    private void startRecord() {
        if (!isRecord) {
            isRecord = true;
            voiceToast.show();
            mAnticlockwise.reStart(TIME_LENGTH);
            try {
                // 设置文件名称
                // 设置sd卡文件路径
                mAudioRecorder = new AudioRecorder();
                mAudioRecorder.start(fileName);
                starMillis = System.currentTimeMillis();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * 停止录音
     */
    private void stopRecord() {
        if (isRecord) {
            isRecord = false;
//            mVoicePopupWindow.dismiss();
            voiceToast.dismiss();
            try {
                mAudioRecorder.stop();
                endMillis = System.currentTimeMillis();
                filePath = mAudioRecorder.sanitizePath(fileName);
                //-----------------------添加数据---------------------
                if ((endMillis - starMillis) > 1000) {
//                    RecordBean bean = new RecordBean();
//                    bean.setFileName(fileName + ".amr");
//                    bean.setFilePath(filePath);
//                    bean.setDuration(Util.formatDecimals(0, (endMillis - starMillis) / 1000 + ""));
//                    mData.add(bean);
                    mRecordAdapter.add(filePath, generateTime(endMillis - starMillis));

                } else {
                    Utility.delete(new File(filePath));
                    Toast.makeText(context, "录音时间太短", Toast.LENGTH_SHORT).show();
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * 将毫秒转时分秒
     *
     * @param time
     * @return
     */
    public static String generateTime(long time) {
        int totalSeconds = (int) (time / 1000);
        int seconds = totalSeconds % 60;
        int minutes = (totalSeconds / 60) % 60;
        int hours = totalSeconds / 3600;

        return hours > 0 ? String.format("%02dh%02d'%02d\"", hours, minutes, seconds) : String.format("%02d'%02d\"", minutes, seconds);
    }

    /**
     * @return 返回音频字符串
     */
    private String getFileBase64(String filePath) {
        if (Utility.isFolderExist(filePath)) {
            // 显示字节数组
            File saveFilePath = new File(filePath);// 返回的音频问题件
            // 音频字符串
            String tapeBase = new String(Base64.encode(Utility.getBytesFromFile(saveFilePath), 0));
            return tapeBase;
        } else {
            return "";
        }
    }

    /**
     * 生命周期销毁方法
     * 1.删除缓存文件
     * 2.停止正在播放语音
     */
    public void onDestroy() {
        //清除缓存文件
        if (!"1".equals(state)) {
            if (Utility.isFolderExist(AudioRecorder.RECORD_PATH)) {
                Utility.delete(new File(AudioRecorder.RECORD_PATH));
            }
        }
        //获取播放器
        MediaPlayer player = mRecordAdapter.getMediaPlayer();
        if (player != null) {
            player.stop();
        }
    }

    public void setPreview(String voicePaths) {
        if (TextUtils.isEmpty(voicePaths)) {
            return;
        }
        mRecordAdapter.setList(Utility.getListByDou(voicePaths));
    }

}
